﻿//using iTextSharp.text.pdf;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using ZhongKeSite.Common.Utility;
using ZhongKeSite.Entity;

namespace ZhongKeSite.Common.Helper
{
    public class FileHelper
    {
        public static string UploadFile(IPathProvider pathProvider, IFormFile formFile)
        {
            string result = string.Empty;
            if (formFile.Length == 0)
                return result;
            string path = string.Format("\\wwwroot{0}", AppSettings.UploadDirPath);
            //文件名
            string newName = IdentityCreator.NextIdentity + Path.GetExtension(formFile.FileName);
            //相对路径
            string virualPath = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd"));
            //保存的物理路径
            string filePath = pathProvider.MapPath(virualPath);
            //返回文件路径
            string returnPath = Path.Combine(AppSettings.UploadDirPath, DateTime.Now.ToString("yyyyMMdd"));
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            result = Path.Combine(filePath, newName);
            using (var stream = new FileStream(result, FileMode.Create))
            {
                formFile.CopyTo(stream);
                stream.Flush();
            }
            return Path.Combine(returnPath, newName);
        }

        public static byte[] GetDownLoadData(string DownLoadUrl)
        {
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
                    var FileByte = webClient.DownloadData(DownLoadUrl);
                    return FileByte;
                }
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 上传服务端文件至文件服务器
        /// </summary>
        /// <returns></returns>
        public static string UploadServerFile(string filePath, string userId, UploadFileType uploadFileType)
        {
            #region 上传到远程文件服务器并删除本地文件
            string fileUrl = string.Empty;
            if (System.IO.File.Exists(filePath))
            {
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
                keyValuePairs.Add("UploadFileType", ((int)uploadFileType).ToString());
                keyValuePairs.Add("UserId", userId);
                keyValuePairs.Add("Token", DESEncrypt.Encrypt(userId, DESEncrypt.Key));
                //上传服务器
                Dictionary<string, StringValues> fields = new Dictionary<string, StringValues>();
                FormFileCollection file = new FormFileCollection();
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
                IFormFile formFile = new FormFile(fs, 0, fs.Length, fs.Name, fs.Name);
                file.Add(formFile);
                IFormFileCollection files = file;
                IFormCollection formData = new FormCollection(fields, files);
                var resultResponse = HttpHelper.HttpUploadFile<ResultResponse<UploadFileInfo>>(string.Format("{0}/File/UploadFiles", AppSettings.FileDomain), System.Text.Encoding.UTF8, formData, keyValuePairs);
                if (resultResponse != null && resultResponse.success)
                {
                    fs.Close();
                    string excelFilePath = resultResponse.data.FilePath;
                    fileUrl = excelFilePath;
                    //string fileDownLoadName = Path.GetFileName(filePath);
                    //fileUrl = CommonHelper.GetJoinUrl(excelFilePath, fileDownLoadName);
                    //System.IO.File.Delete(filePath);
                }
            }
            return fileUrl;
            #endregion
        }


        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片地址</param>
        /// <param name="dFile">压缩后保存图片地址</param>
        /// <param name="flag">压缩质量（数字越小压缩率越高）1-100</param>
        /// <param name="size">压缩后图片的最大大小</param>
        /// <param name="sfsc">是否是第一次调用</param>
        /// <returns></returns>
        public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true)
        {
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            //如果是第一次调用，原始图像的大小小于要压缩的大小，则直接复制文件，并且返回true
            FileInfo firstFileInfo = new FileInfo(sFile);
            if (sfsc == true && firstFileInfo.Length < size * 1024)
            {
                firstFileInfo.CopyTo(dFile);
                return true;
            }

            int dHeight = iSource.Height;
            int dWidth = iSource.Width;

            Size tem_size = new Size(iSource.Width, iSource.Height);
            int sW = tem_size.Width, sH = tem_size.Height;

            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();

            //以下代码为保存图片时，设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;

            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                    FileInfo fi = new FileInfo(dFile);
                    if (fi.Length > 1024 * size)
                    {
                        flag = flag - 10;
                        CompressImage(sFile, dFile, flag, size, false);
                    }
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }


        //public static int GetPDFPageTotal(byte[] pdfIn)
        //{
        //    using (PdfReader reader = new PdfReader(pdfIn))
        //    {
        //        int iPageNum = reader.NumberOfPages;
        //        return iPageNum;
        //    }
        //}

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="name">文件名</param>
        /// <param name="path">路径</param>
        /// <returns>运行结果</returns>
        public static bool FileDownload(string url, string path)
        {
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
                    webClient.DownloadFile(url, path);
                    return true;
                }

            }
            catch
            {
                return false;
            }
        }

    }
}
